<template>
  <Modal
    v-model:active="simrightFileSelectModalActive"
    title="在Simright 3DLite中打开"
    hide-mask
    @confirm="submit"
  >
    <div>
      <div class="file-select">
        <span>选择文件</span>
        <Input class="w-300 ml-8" v-model:value="ossFile" />
        <Button class="ml-8" @click="openResultLibraryModal">选择</Button>
      </div>
      <div class="flex mt-10">
        <span>文件类型</span>
        <Select v-model:value="fileType" class="w-100 ml-8" :options="options">
        </Select>
      </div>
      <div class="flex mt-10">
        <span>转换进度</span>
        <Progress :percentage="progress" class="w-300 ml-20"></Progress>
      </div>
    </div>
  </Modal>
</template>
<script lang="ts" setup>
import { Modal, Input, Button, Progress, Select, Option, Toast } from "cax-ui";
import { ref } from "vue";
import { useCoreStore } from "@/UI/store";
import { storeToRefs } from "pinia";
import { submitTask, isExist, getTaskStatus } from "@/UI/api/shuqiao";
import { AppEvent } from "@/UI/config";
const coreStore = useCoreStore();
const { simrightFileSelectModalActive } = storeToRefs(coreStore);
const progress = ref(0);
const ossFile = ref("");
const fileType = ref("rst");
const options = [
  {
    label: "vtk",
    value: "vtk",
  },
  {
    label: "hdf5",
    value: "hdf5",
  },
  {
    label: "rst",
    value: "rst",
  },
];

coreStore.Notify.subscribe((msg) => {
  if (msg.type === AppEvent.RESULT_LIBRARY_SELECTED) {
    ossFile.value = msg.data;
  }
});

function submit() {
  isExist(ossFile.value).then((res) => {
    // * 还没有存在
    if (res.code === -1) {
      const fileName = ossFile.value.split("/").pop() as string;
      /**
       * @发起任务请求
       */
      Toast.loading({
        content: "任务正在处理中",
        duration: -1,
      });
      submitTask(ossFile.value, fileName).then((res) => {
        if (res.code === 0) {
          let timer = setInterval(() => {
            getTaskStatus(res.data.taskId).then((r) => {
              progress.value = r.data.progress;
              console.log("数巧返回", r.data);
              if (r.data.url) {
                clearInterval(timer);
                Toast.close();
                window.open(r.data.url);
              } else if (r.data.status === "failure") {
                clearInterval(timer);
              }
            });
          }, 1000);
        }
      });
    } else {
      // * 已经存在
      if (res.data && res.data.viewDataUrl) {
        window.open(res.data.viewDataUrl);
      }
    }
  });
}

function openResultLibraryModal() {
  coreStore.updateResultLibraryModalActive(true);
}
</script>
<style lang="less" scoped>
.file-select {
  width: 500px;
}
</style>
